package com.rx.action.admin.sys;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang.ArrayUtils;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;
import org.springside.modules.utils.web.struts2.Struts2Utils;

import com.rx.action.BaseAction;
import com.rx.biz.BaseBiz;
import com.rx.biz.sys.UserBiz;
import com.rx.common.Constants;
import com.rx.common.exception.ServiceException;
import com.rx.common.exception.ValidateException;
import com.rx.entity.sys.Role;
import com.rx.entity.sys.User;
import com.rx.util.PasswordEncoderUtils;

import flexjson.JSONSerializer;

@Namespace("/admin/sys")
@Results( { @Result(name = BaseAction.RELOAD, location = "user.action?page.pageNo=${page.pageNo}", type = "redirect") })
public class UserAction extends BaseAction<User, Long> {

	/**
	 * 序列化
	 */
	private static final long serialVersionUID = 1L;

	@Resource(name = "userBiz")
	public void setBiz(BaseBiz<User, Long> biz) {
		super.biz = biz;
	}

	/* 高级查询 */
	private String filter_LIKES_name;
	private String filter_LIKES_code;
	/* 原密码 */
	private String orgPassWord = null;

	/**
	 * list
	 */
	@Override
	public String list() throws Exception {

		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(Struts2Utils.getRequest());
		if (!page.isOrderBySetted()) {
			page.setOrderBy("id");
			page.setOrder(Page.DESC);
		}
		page = biz.search(page, filters);

		return SUCCESS;
	}

	/**
	 * input
	 */
	@Override
	public String input() throws Exception {
		// 修改
		if (id != null) {
			// 密码设置成空密码
			entity.setPassWord(Constants.BLANK_PASSWORD);
		}
		return INPUT;
	}

	/**
	 * save
	 */
	@Override
	public String save() throws Exception {

		try {
			isValidate(new Object[] { entity.getUserName(),
					entity.getPassWord(), entity.getName(), entity.getCode() },
					new String[] { "账号", "密码", "名称", "编号" });
		} catch (ValidateException e) {
			return INPUT;
		}

		// 添加
		if (id == null) {
			// 检查账号是否重复
			User user = ((UserBiz) biz)
					.findUserByUserName(entity.getUserName());
			if (user != null) {
				addActionMessage("对不起，账号已经存在！");
				return INPUT;
			}
		}

		// 角色列表
		String[] roleIds = Struts2Utils.getRequest().getParameterValues(
				"roleIds");
		Set<Role> roles = new HashSet<Role>();
		if (ArrayUtils.isNotEmpty(roleIds)) {
			for (String roleId : roleIds) {
				Role role = new Role();
				role.setId(Long.parseLong(roleId));

				roles.add(role);
			}
		}
		entity.setRoles(roles);

		setBaseProperty(entity);

		// 没有修改密码
		if (entity.getPassWord().equals(Constants.BLANK_PASSWORD)) {
			entity.setPassWord(orgPassWord);
		} else {
			// 密码加密
			entity.setPassWord(PasswordEncoderUtils.encodePassword(entity
					.getPassWord()));
		}

		biz.save(entity);
		addActionMessage("保存成功");

		return RELOAD;
	}

	@Override
	protected void prepareModel() throws Exception {
		super.prepareModel();
		if (id != null) {
			orgPassWord = entity.getPassWord();
		}
	}

	/**
	 * delete
	 */
	@Override
	public String delete() throws Exception {

		try {
			String[] ids = getParameterValues("oid");
			if (ArrayUtils.isNotEmpty(ids)) {
				for (String id : ids) {
					biz.delete(Long.parseLong(id));
				}
			}
			addActionMessage("删除成功");
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			addActionMessage("删除失败");
		}

		return RELOAD;
	}

	/**
	 * 用户树
	 * 
	 * @return
	 * @throws Exception
	 */
	public String tree() throws Exception {
		// 全部用户
		List<User> users = biz.search();
		// 根节点
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("text", "根目录");
		root.put("expanded", "true");
		root.put("classes", "folder");
		// 子节点
		List<Map<String, String>> children = new ArrayList<Map<String, String>>();
		for (User user : users) {
			Map<String, String> child = new HashMap<String, String>();
			child.put("id", user.getId().toString());
			child.put("text",
					"<label><input type='checkbox' name='user_id' value='"
							+ user.getId() + "'/>" + user.getName()
							+ "</label>");
			child.put("classes", "file");

			children.add(child);
		}
		root.put("children", children);
		// JSON
		StringBuffer json = new StringBuffer();
		json.append("[");
		json.append(new JSONSerializer().serialize(root));
		json.append("]");
		Struts2Utils.renderJson(json.toString());
		return null;
	}

	public String getFilter_LIKES_name() {
		return filter_LIKES_name;
	}

	public void setFilter_LIKES_name(String filterLIKESName) {
		filter_LIKES_name = filterLIKESName;
	}

	public String getFilter_LIKES_code() {
		return filter_LIKES_code;
	}

	public void setFilter_LIKES_code(String filterLIKESCode) {
		filter_LIKES_code = filterLIKESCode;
	}

}